import React, { Component } from 'react'
import {
  Text,
  View,
  StyleSheet,
  Platform,
  Animated,
  ScrollView,
  TouchableOpacity,
  PixelRatio,
  Image,
  Keyboard,
  TextInput,
  Dimensions,
  KeyboardAvoidingView,
  DeviceEventEmitter,
} from 'react-native'
import Immutable from 'immutable'
import Icon from 'react-native-vector-icons/Ionicons'
import Loader from '../component/Loader'
import Button from '../component/Button'
import RootView from '../component/RootView'
import Base from './Base'
import {
  imageServer,
  NavigationActions,
  createAction,
  px2dp,
  isIos,
  getBorderWidth,
  accAdd,
  accSub,
  getAsyncStorage,
} from '../utils'
import { toast } from '../utils/toast'
import * as productService from '../services/product'
import * as cartService from '../services/cart'

const { width, height } = Dimensions.get('window')
const borderWidth = getBorderWidth()
const cartHeight = Platform.OS === 'ios' ? 46 : 46
const barHeight = Platform.OS === 'ios' ? 64 : 80

class Goods extends Base {
  constructor(props) {
    super(props)
    this.state = {
      displayLoader: true,
      products: [],
      goods: {},
      shiptime: 60,
      stock: {},
      buyCount: 1,
      totalPrice: 0,
      activeSpec: 0,
      notConnected: false,
    }
    this.keyboardDidHideListener = null
    this.subscription=null
  }
  static navigationOptions = {
    title: '商品详情',
    headerBackTitle: null,
    headerTitleStyle: {
      alignSelf: 'center',
    },
    headerStyle: {
      backgroundColor: 'white',
      borderBottomWidth: 0,
      shadowColor: 'transparent',
      elevation: 1,
    },
    headerRight: <View />,
  }
  loadData() {
    let { goodsId, isSku } = this.props.navigation.state.params

    if (!isSku) {
      isSku = 0
    }
    getAsyncStorage('STOREID')
      .then(data => {
        getAsyncStorage('CONFIG')
          .then(jsonConfig => {
            const storeId = data
            const config = JSON.parse(jsonConfig)
            productService
              .detail({ id: goodsId, storeId, isSku })
              .then(data => {
                this.loadCart(cartData => {
                  const products = data.data.products

                  this.setState({
                    displayLoader: false,
                    notConnected: false,
                    totalPrice: cartData.totalPrice,
                    adwords:data.data.adwords,
                    goods: data.data.goods,
                    products,
                    stock: data.data.stock,
                    activeSpec: data.data.activeSpec,
                    shiptime: config.shiptime || 60,
                  })
                })
              })
              .catch(e => {
                this.checkError(e, { displayLoader: false })
              })
          })
          .catch(e => {
            this.checkError({ msg: '读取配置缓存出错' }, { displayLoader: false })
          })
      })
      .catch(e => {
        // error
        this.checkError({ msg: '位置不在服务范围内' }, { displayLoader: false })
      })
  }
  onEvent(key){
    if (key != 'goods') {
      this.loadCart()
    }
  }
  loadCart(fn) {
    cartService.queryLocal().then(data => {
      // 数据处理
      let str = ''
      let unchecked = ''
      data.map((item, i) => {
        // 获取未被选中的item
        if (!item.checked) {
          unchecked += `${item.id}#`
        }
        str += `|${item.id}#${item.num}`
      })
      cartService
        .view({ data: str, unchecked })
        .then(data => {
          if (!fn) {
            this.setState({
              totalPrice: data.totalPrice,
            })
          } else {
            fn(data)
          }
        })
        .catch(e => {
          this.checkError(e)
        })
    })
  }
  addCart() {
    const { products, stock, activeSpec, buyCount } = this.state
    const productInfo = products[activeSpec]
    const stockMap = stock[String(productInfo.id)]

    if (!stockMap || stockMap.num <= 0) {
      toast('商品库存不足')
      return
    }
    const params = {
      id: productInfo.id,
      checked: true,
      num: parseInt(buyCount),
    }
    cartService.writeLocal(params).then(data => {
      // 发送刷新事件
      DeviceEventEmitter.emit('cart.reload','goods')
      this.loadCart()
    })
  }
  async createOrder() {
    await this.checkLogin()
    const { products, activeSpec, buyCount } = this.state
    const productInfo = products[activeSpec]
    const params = {
      data: `${productInfo.id}#${buyCount}`,
    }
    this.goto('OrderConfirm', params)
  }
  addItem() {
    // 数量不能超过库存
    const { buyCount, stock, products, activeSpec } = this.state
    const obj = stock[String(products[activeSpec].id)]
    if (!obj || (obj && obj.num <= parseInt(buyCount))) {
      toast('商品库存不足')
      return
    }
    this.setState({
      buyCount: parseInt(buyCount) + 1,
    })
  }
  minusItem() {
    const { buyCount } = this.state
    if (parseInt(buyCount) < 2) {
      toast('至少购买一件')
      return
    }
    this.setState({
      buyCount: parseInt(buyCount) - 1,
    })
  }
  onChangeText(text) {
    this.setState({
      buyCount: text,
    })
  }
  onKeyboardDidHide() {
    if (!this.state.buyCount) {
      this.setState({
        buyCount: 1,
      })
    }
  }
  renderSpec() {
    const { products, activeSpec } = this.state
    return products.map((item, i) => {
      let backgroundColor = '#f6f6f6'
      let color = '#333'
      if (i == activeSpec) {
        backgroundColor = '#e23f3c'
        color = 'white'
      }
      return (
        <TouchableOpacity
          key={i}
          style={[styles.spec, { backgroundColor }]}
          onPress={() => {
            if (activeSpec != i) {
              this.setState({ activeSpec: i, buyCount: 1 })
            }
          }}
        >
          <Text style={{ color }}>{item.spec}</Text>
        </TouchableOpacity>
      )
    })
  }
  renderCartView() {
    const { totalPrice } = this.state
    return (
      <View style={styles.cartView}>
        <View style={styles.cartCol}>
          <TouchableOpacity
            style={[styles.iconWrap]}
            onPress={() => this.goto('CartSingle')}
          >
            <View style={[styles.iconView]}>
              <Icon name="ios-cart-outline" size={px2dp(32)} color="#999" />
            </View>
            <View style={[styles.count]}>
              <Text style={{ fontSize: px2dp(10), color: '#fff' }}>
                ¥{totalPrice}
              </Text>
            </View>
          </TouchableOpacity>
        </View>
        <View style={styles.cartCol}>
          <View style={{ flexDirection: 'row' }}>
            <TouchableOpacity
              style={[styles.buttonWrap, { backgroundColor: '#de6816' }]}
              onPress={() => this.addCart()}
            >
              <Text style={[styles.button]}>加入购物车</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.buttonWrap, { backgroundColor: '#e23f3c' }]}
              onPress={() => this.createOrder()}
            >
              <Text style={[styles.button]}>立即购买</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    )
  }
  componentWillUnmount() {
    this.keyboardDidHideListener.remove()
    this.subscription.remove()
  }
  componentDidMount() {
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () =>
      this.onKeyboardDidHide()
    )
    this.subscription = DeviceEventEmitter.addListener(
      'cart.reload',
      this.onEvent.bind(this)
    )
    this.loadData()
  }

  render() {
    const {
      fetching,
      displayLoader,
      goods,
      products,
      stock,
      buyCount,
      activeSpec,
      notConnected,
      shiptime,
      adwords,
    } = this.state
    if (products.length == 0) {
      return <Loader loading={displayLoader} />
    }
    let stockAmount = 0
    const product = products[activeSpec]
    const stockMap = stock[String(product.id)]
    if (stockMap) {
      stockAmount = stockMap.num
    }
    let ship = `${shiptime}分钟送达`
    if (shiptime >= 60) {
      ship = `${shiptime / 60}小时送达`
    }
    return (
      <RootView
        notConnected={notConnected}
        fetching={fetching}
        onReconnect={() => this.loadData()}
        style={styles.container}
      >
        <KeyboardAvoidingView
          behavior="position"
          contentContainerStyle={{ height: height - cartHeight - barHeight }}
        >
          <ScrollView
            showsHorizontalScrollIndicator={false}
            showsVerticalScrollIndicator={false}
            style={{ flex: 1 }}
          >
            <View
              style={{

                height: width-40,
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <Image

                style={{ width: width-40, height: width-40 }}

                source={{ uri: imageServer + product.image }}
              />
            </View>
            <View style={{ paddingHorizontal: 16, paddingVertical: 8 }}>
              <View style={{ marginVertical: 10 }}>
                <Text
                  style={{ color: '#e23f3c', fontWeight: 'bold', fontSize: 16 }}
                >
                  ￥{product.salePrice}
                </Text>
              </View>
              <View style={{ flexDirection: 'row' }}>
                <Text
                  style={{
                    flex: 1,
                    textDecorationLine:'line-through',
                    color: '#999',
                    marginBottom: 10,
                  }}
                >
                  ￥{product.retailPrice}
                </Text>
              </View>
              <Text>{goods.name}</Text>
              {
                adwords?<Text style={{ color: '#e23f3c',marginTop: 10}}>{adwords}</Text>:null
              }
              
              <View style={{ marginTop: 10, flexDirection: 'row' }}>
                <Text style={{ color: '#999', marginRight: 10 }}>
                  月售{goods.volume || 0}件
                </Text>
                <Text style={{ color: '#999', marginRight: 10 }}>
                  库存{stockAmount}件
                </Text>
                <Text style={{ color: '#999' }}>评分{goods.rate || '5.0'}</Text>
              </View>
              <View
                style={{
                  display: 'flex',
                  flexWrap: 'wrap',
                  marginTop: 10,
                  flexDirection: 'row',
                }}
              >
                {this.renderSpec()}
              </View>
              <View
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  marginTop: 10,
                  flexDirection: 'row',
                }}
              >
                <Icon
                  name="ios-checkmark-circle"
                  size={18}
                  style={{ color: '#999' }}
                />
                <Text style={{ fontSize: 12, color: '#999', marginLeft: 5 }}>
                  正品保障
                </Text>
                <Icon
                  name="ios-checkmark-circle"
                  size={18}
                  style={{ color: '#999', marginLeft: 15 }}
                />
                <Text style={{ fontSize: 12, color: '#999', marginLeft: 5 }}>
                  {ship}
                </Text>
              </View>
              <View style={[styles.item2, { marginTop: 15 }]}>
                <View style={{ width: 100, justifyContent: 'center' }}>
                  <Text>品牌</Text>
                </View>
                <View
                  style={{
                    flex: 1,
                    justifyContent: 'center',
                    alignItems: 'flex-end',
                  }}
                >
                  <Text>{goods.brand}</Text>
                </View>
              </View>

              <View style={[styles.item2]}>
                <View style={{ width: 100, justifyContent: 'center' }}>
                  <Text>购买数量</Text>
                </View>
                <View style={styles.actionView}>
                  <TouchableOpacity
                    style={styles.minusBtn}
                    onPress={() => this.minusItem()}
                  >
                    <Icon
                      name={'ios-remove-circle-outline'}
                      size={px2dp(24)}
                      color="#999"
                    />
                  </TouchableOpacity>
                  <TextInput
                    value={String(buyCount)}
                    keyboardType="numeric"
                    underlineColorAndroid="transparent"
                    onChangeText={text => this.onChangeText(text)}
                    style={{
                      padding: 0,
                      width: 25,
                      textAlign: 'center',
                      color: '#333',
                    }}
                  />
                  <TouchableOpacity
                    style={styles.addBtn}
                    onPress={() => this.addItem()}
                  >
                    <Icon
                      name={'ios-add-circle-outline'}
                      size={px2dp(24)}
                      color="#999"
                    />
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          </ScrollView>
        </KeyboardAvoidingView>
        {this.renderCartView()}
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  spec: {
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: isIos() ? 8 : 0,
    paddingVertical: 4,
    paddingHorizontal: 12,
    marginRight: 8,
    marginBottom: 8,
  },
  item2: {
    flexDirection: 'row',
    backgroundColor: 'white',
    paddingVertical: 10,
    borderColor: '#f0f0f0',
    borderTopWidth: borderWidth,
  },
  minusBtn: {
    backgroundColor: 'transparent',
  },
  addBtn: {
    backgroundColor: 'transparent',
  },

  actionView: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
    backgroundColor: 'transparent',
  },
  cartView: {
    height: cartHeight,
    backgroundColor: '#fff',
    flexDirection: 'row',
    elevation: 5, // for android
    shadowOffset: { width: 0, height: 0 },
    shadowColor: '#e5e5e5',
    shadowOpacity: 0.85,
    shadowRadius: 5,
  },
  cartCol: {
    flex: 1,
  },
  iconWrap: {
    position: 'absolute',
    left: 16,
    top: 0,
    width: 100,
    height: 46,
  },
  iconView: {
    width: 46,
    height: 46,
    alignItems: 'center',
    justifyContent: 'center',
  },
  count: {
    backgroundColor: '#f00',
    height: 14,
    borderRadius: 7,
    overflow: 'hidden',
    paddingHorizontal: 4,
    paddingVertical: 1,
    alignItems: 'center',
    justifyContent: 'center',
    position: 'absolute',
    top: 6,
    left: 28,
  },
  buttonWrap: {
    flex: 1,
    height: cartHeight,
    alignItems: 'center',
    justifyContent: 'center',
  },
  button: {
    color: 'white',
  },
})

export default Goods
